﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using WucCloud.Utility;

namespace WucCloud.WebApi
{
    /// <summary>
    /// JWT鉴权 拓展
    /// </summary>
    public static class JwtExtension
    {       
        /// <summary>
        /// JWT鉴权 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddJWTPower(this IServiceCollection services)
        {
            #region Jwt授权
            services.AddAuthentication(x =>
                        {
                            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                        }).AddJwtBearer(jwtOptions =>
                        {
                            byte[] btKey = Encoding.UTF8.GetBytes(GlobalContext.AppSettingConfig.SecretKey);
                            SecurityKey securityKey = new SymmetricSecurityKey(btKey);
                            jwtOptions.TokenValidationParameters = new TokenValidationParameters
                            {
                                IssuerSigningKey = securityKey,
                                //将用于检查令牌的发行者是否与此发行者相同。
                                ValidIssuer = GlobalContext.AppSettingConfig.Issuer,
                                //是否验证发行者
                                ValidateIssuer = true,
                                //检查令牌的受众群体是否与此受众群体相同。
                                ValidAudience = GlobalContext.AppSettingConfig.Audience,
                                //在令牌验证期间验证受众 .
                                ValidateAudience = true,
                                //验证生命周期
                                ValidateLifetime = true,
                                // The signing key must match!
                                //是否调用对签名securityToken的SecurityKey进行验证。
                                ValidateIssuerSigningKey = true,
                                //允许服务器时间偏移量300秒
                                ClockSkew = TimeSpan.FromSeconds(300)
                            };
                        });
            #endregion

            return services;
        }
    }
}
